package com.hp.interview.optimize;

import lombok.AllArgsConstructor;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * TODO 注释
 *
 * @author hupan
 * @date 2021-06-03 21:41
 */
public class HashMapOptimize {

    public void test1() {
        long start = System.currentTimeMillis();
        Map<String, Person1> map = new HashMap<>();
        for (int i = 0; i < 10000000; i++) {
            map.put("s" + i, new Person1("s" + i, "addr" + i, i));
        }

        long end = System.currentTimeMillis();

        System.out.println("耗时：" + (end - start));
    }

    public void test2() {
        long start = System.currentTimeMillis();
        Map<String, Person2> map = new HashMap<>();
        for (int i = 0; i < 10000000; i++) {
            map.put("s" + i, new Person2("s" + i, "addr" + i, i));
        }


        long end = System.currentTimeMillis();

        System.out.println("耗时：" + (end - start));
    }

    public static void main(String[] args) {
        Person1 p1 = new Person1("a", "shanghai", 20);
        Person2 p2 = new Person2("b", "beijing", 22);

        int n = 16;

        int h = 0;
        int h1 = (h = p1.hashCode()) ^ (h >>> 16);
        int h2 = (h = p2.hashCode()) ^ (h >>> 16);

        System.out.println((n - 1) & h1);
        System.out.println((n - 1) & h2);
    }

}

@AllArgsConstructor
class Person1 {
    String name;
    String addr;
    int age;
}

@AllArgsConstructor
class Person2 {
    String name;
    String addr;
    int age;

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }

        if (o == null || getClass() != o.getClass()) {
            return false;
        }

        Person2 person2 = (Person2) o;

        return age == person2.age && Objects.equals(name, person2.name) && Objects.equals(addr, person2.addr);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, addr, age) >>> 16;
    }
}